#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QWebSocket>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent),
    ui(new Ui::MainWindow),
    is_listen(false)
{
    ui->setupUi(this);

    ui->url->setEnabled(false);
    ui->url->setText("any");
    ui->port->setText("38888");
    ui->close->setEnabled(false);

    websocket_server = new QWebSocketServer(QStringLiteral("OCPP Server"), QWebSocketServer::NonSecureMode, this);
}

MainWindow::~MainWindow()
{
    websocket_server->close();

    if (websocket_server) {
        delete websocket_server;
    }

    delete ui;
}

void MainWindow::on_listen_clicked()
{
    is_listen = true;

    if (!websocket_server->listen(QHostAddress::Any, ui->port->text().toInt())) {
        return;
    }

    connect(websocket_server, &QWebSocketServer::newConnection, this, &MainWindow::onNewConnection);

    ui->port->setEnabled(false);
    ui->listen->setEnabled(false);
    ui->close->setEnabled(true);
}

void MainWindow::on_close_clicked()
{
    is_listen = false;

    websocket_server->close();

    ui->port->setEnabled(true);
    ui->listen->setEnabled(true);
    ui->close->setEnabled(false);
}

void MainWindow::on_clean_clicked()
{
    ui->show->clear();
}

void MainWindow::onNewConnection()
{
    QWebSocket *client = websocket_server->nextPendingConnection();

    if (!client) {
        return;
    }

    ui->show->append("[" + client->peerAddress().toString() + "] Connected");
    connect(client, &QWebSocket::textMessageReceived, this, &MainWindow::onTextMessageReceived);
    connect(client, &QWebSocket::disconnected, this, &MainWindow::onClientDisconnected);
}

void MainWindow::onClientDisconnected()
{
    QWebSocket *client = qobject_cast<QWebSocket *>(sender());

    if (!client) {
        return;
    }

    client->deleteLater();

    ui->show->append("[" + client->peerAddress().toString() + "] Disconnected");
}

void MainWindow::onTextMessageReceived(const QString &message)
{
    QWebSocket *client = qobject_cast<QWebSocket *>(sender());

    if (!client) {
        return;
    }

    ui->show->append("[" + client->peerAddress().toString() + "]" + message);
}
